//
//  ZWaitReplyViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/3/28.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZWaitReplyViewController.h"
#import "ZConsultTableViewCell.h"
#import "ZConsultModel.h"
#import "ZLookFriendDeatilViewController.h"
#import "ZReplyDetailedViewController.h"
#import "ZValuationViewController.h"
#import "ZOnceSubmitViewController.h"
#import "ZNodoctorViewController.h"
#import "SPVoiceManager.h"
#import "SPPlaceholderCell.h"

static NSString *const placeCellID = @"placeholders";
static NSString * const KZNewMyAskUntilIdentifier = @"KZNewMyAskUntilIdentifier";
static int  page = 1;
@interface ZWaitReplyViewController ()<UITableViewDelegate,UITableViewDataSource>

//@property (nonatomic,strong)ZMyAskUntilView * AskUntilView;  // 未回复
@property (nonatomic,strong)UITableView * waitMainTabView;
@property (nonatomic,strong)LZUserInfo * userInfo;
@property (nonatomic,strong)NSMutableArray <ZConsultModel *> * modelArray;
@property (nonatomic,assign) BOOL isHaveData;
@end

@implementation ZWaitReplyViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([[SPVoiceManager defaultManager] isPlaying]) {
        [[SPVoiceManager defaultManager] stop];
    }
//    [self.waitMainTabView.mj_header beginRefreshing];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _userInfo = [LZUserInfo getUserInfo];
    self.isHaveData = YES;
    self.modelArray = [@[] mutableCopy];
    [self.view addSubview:self.waitMainTabView];
    [self.waitMainTabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
        [self.waitMainTabView.mj_header beginRefreshing];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh0:) name:@"refresh0" object:nil];
}
- (void)refresh0:(NSNotification *)info
{
    
    [self.waitMainTabView.mj_header beginRefreshing];
}

// 表格视图协议
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.isHaveData ? self.modelArray.count : 1 ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (self.isHaveData == YES) {
        ZConsultTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KZNewMyAskUntilIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.cModel = self.modelArray[indexPath.row];
        cell.GoRescindBlock = ^() {
            [weakSelf cancelNetWorking:indexPath.row];
        };
        return cell;
    }else {
        SPPlaceholderCell *cell = [tableView dequeueReusableCellWithIdentifier:placeCellID];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == YES) {
        return 160*ysIZE;
    }else {
        return  SCREEN_Height-104;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == NO) {
        return;
    }
    ZConsultModel * model = self.modelArray[indexPath.row];
    if ([model.status isEqualToString:@"1"]) {
        ZOnceSubmitViewController * ZOSVC =[[ZOnceSubmitViewController alloc] init];
        ZOSVC.qId = model.qId;
        ZOSVC.ishiden = YES;
        [self.navigationController pushViewController:ZOSVC animated:YES];
    }else if ([model.status isEqualToString:@"2"]){
        ZReplyDetailedViewController * ZRDVC = [[ZReplyDetailedViewController alloc] init];
        ZRDVC.qId = model.qId;
        ZRDVC.ishiden = YES;
        //        ZRDVC.personModel = pmodel;
        [self.navigationController pushViewController:ZRDVC animated:YES];
    }else if ([model.status isEqualToString:@"3"]) {
        ZValuationViewController * zvVC = [[ZValuationViewController alloc] init];
        zvVC.qId = model.qId;
        //        zvVC.personModel = pmodel;
        zvVC.ishiden = YES;
        [self.navigationController pushViewController:zvVC animated:YES];
    }else if ([model.status isEqualToString:@"4"]){
        ZLookFriendDeatilViewController * zlVC = [[ZLookFriendDeatilViewController alloc] init];
        zlVC.qId = model.qId;
        zlVC.ishiden = YES;
        [self.navigationController pushViewController:zlVC animated:YES];
    }else {
        ZNodoctorViewController * noDVc = [[ZNodoctorViewController alloc] init];
        noDVc.qId = model.qId;
        noDVc.ishiden = YES;
        [self.navigationController pushViewController:noDVc animated:YES];
    }
}


- (void)waitRePlyNetWorking {
    page = 1;
    self.isHaveData = YES;
    NSDictionary * wDict = @{@"uid":_userInfo.uid,@"type":@"1",@"p":[NSString stringWithFormat:@"%d",page]};
    [YJProgressHUD showProgress:@"刷新中" inView:self.view];
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:wDict paramarsSite:@"Consult/index" sucessBlock:^(id content) {
        NSDictionary * zzdict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([zzdict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
            [self handleDataWithArray:zzdict[@"list"]];
        }else {
            self.isHaveData = NO;
            [self.waitMainTabView reloadData];
            [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        self.isHaveData = NO;
        [self.waitMainTabView reloadData];
        [YJProgressHUD showMessage:@"网络请求失败" inView:self.view];
    }];
}
- (void)waitMoreRePlyNetWorking {
    page++;
    NSDictionary * wDict = @{@"uid":_userInfo.uid,@"type":@"1",@"p":[NSString stringWithFormat:@"%d",page]};
    [YJProgressHUD showProgress:@"刷新中" inView:self.view];
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:wDict paramarsSite:@"Consult/index" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
            [self handleMoreDataWithArray:dict[@"list"]];
        }else {
            [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"网络请求失败" inView:self.view];
    }];

}

- (void)handleDataWithArray:(NSArray *)array {
    [self.waitMainTabView.mj_footer resetNoMoreData];
    [self.modelArray removeAllObjects];
    if (array.count == 0) {
        self.isHaveData = NO;
        [YJProgressHUD showMessage:@"已无更多案例" inView:self.view];
        [self.waitMainTabView.mj_footer endRefreshingWithNoMoreData];
        return;
    }else if (array.count < 10) {
        [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
        [self.waitMainTabView.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSMutableDictionary * dict in array) {
        ZConsultModel * model = [[ZConsultModel alloc] initWithDict:dict];
        [self.modelArray addObject:model];
    }
    [self.waitMainTabView reloadData];
}
- (void)handleMoreDataWithArray:(NSArray *)array {
    [self.waitMainTabView.mj_footer resetNoMoreData];
    if (array.count == 0) {
        [YJProgressHUD showMessage:@"已无更多案例" inView:self.view];
        [self.waitMainTabView.mj_footer endRefreshingWithNoMoreData];
        return;
    }else if (array.count < 10) {
        [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
        [self.waitMainTabView.mj_footer endRefreshingWithNoMoreData];
    }
    for (NSMutableDictionary * dict in array) {
        ZConsultModel * model = [[ZConsultModel alloc] initWithDict:dict];
        [self.modelArray addObject:model];
    }
    [self.waitMainTabView reloadData];
}

// 撤销的网络请求
- (void)cancelNetWorking:(NSInteger)index {
    
    NSDictionary * dict = @{@"id":_modelArray[index].qId,@"uid":_userInfo.uid};
    [YJProgressHUD showProgress:@"撤销中" inView:self.view];
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:dict paramarsSite:@"Consult/revocation" sucessBlock:^(id content) {
        NSDictionary * wdict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([wdict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"撤销成功" inView:self.view];
            [self renovate:index];
        }else {
            [YJProgressHUD showMessage:@"撤销失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"网络请求失败" inView:self.view];
    }];
}
-(void)renovate :(NSInteger)index{
//    [self.waitMainTabView.mj_header beginRefreshing];
    [_modelArray removeObjectAtIndex:index];
    [self.waitMainTabView reloadData];
}
- (UITableView *)waitMainTabView {
    if (_waitMainTabView) {
        return _waitMainTabView;
    }
    _waitMainTabView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _waitMainTabView.dataSource = self;
    _waitMainTabView.delegate = self;
//    _waitMainTabView.rowHeight = 160*ysIZE;
    _waitMainTabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_waitMainTabView registerNib:[UINib nibWithNibName:NSStringFromClass([SPPlaceholderCell class]) bundle:nil] forCellReuseIdentifier:placeCellID];
    [_waitMainTabView registerClass:[ZConsultTableViewCell class] forCellReuseIdentifier: KZNewMyAskUntilIdentifier];
    _waitMainTabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self waitRePlyNetWorking];
        [_waitMainTabView.mj_header endRefreshing];
    }];
    _waitMainTabView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self waitMoreRePlyNetWorking];
        [_waitMainTabView.mj_footer endRefreshing];
    }];

    return _waitMainTabView;
}
@end
